<?php

namespace Managers\Utils;

require_once 'PHPExcel.php';

class Export
{
    const CREATOR = 'Mallards swim team';
    const TITLE = 'Mallards swim team';
    const DIR_TO_SAVE = '/export/';
    const FILE_NAME = 'export.xlsx';

    /**
     * @var PHPExcel
     */
    protected $_objExcel = null;

    function __construct()
    {
        $this->_objExcel = new \PHPExcel();
        $this->_objExcel->getProperties()->setCreator(self::CREATOR)
                ->setTitle(self:: TITLE);
    }

    function addData($data, $filter, $sheet = 0)
    {
        //Заголовок таблицы.

        foreach ($filter as $iter => $record) {
            $this->_objExcel->setActiveSheetIndex($sheet)
                    ->setCellValueByColumnAndRow($iter, 1, $record);
        }

        //Данные. Начинаем запись с B ячейки.
        $start = 2;
        foreach ($data as $row => $value) {
            $column = 0;
            foreach ($filter as $record) {
                $this->_objExcel->setActiveSheetIndex($sheet)
                        ->setCellValueByColumnAndRow($column, $start + $row, $value[$record]);
                $column++;
            }
        }

        return $this;
    }

    function getDocument()
    {
        $objWriter = \PHPExcel_IOFactory::createWriter($this->_objExcel, 'Excel2007');
        $url = preg_replace('/\/{2,}/', '/', self::DIR_TO_SAVE . DIRECTORY_SEPARATOR . self::FILE_NAME);
        $file = preg_replace('/\/{2,}/', '/', dirname(APPLICATION_PATH) . DIRECTORY_SEPARATOR . 'public'
                                              . DIRECTORY_SEPARATOR . $url);
        if (!is_writable(dirname($file))) {
            throw new \Exception(dirname($file) . ' is not writable.');
        }
        $objWriter->save($file);
        return $url;
    }
}

?>